﻿using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;

using gKodes.Drawing;
using gKodes.Collections;

namespace gKodes.Windows.Forms.Internals
{
    public class TextSegment : HexView.PageSegment
    {
        private const string Unreadable = ".";

        public override string Name
        {
            get { return "Text"; }
        }

        public override bool IsNavigable
        {
            get { return true; }
        }

        public override bool CanSelect
        {
            get { return true; }
        }

        public override void ResizeTo(Size size)
        {
            HexView.PageSegment mHVPainter = (HexView.PageSegment)this.FindSegment("Hex");
            if (mHVPainter == null || !mHVPainter.Visible)
                base.ResizeTo(size);
            else
            {
                //Size tSize = this.GetCellSize();
                if (this.CellSize.Width > 0 && this.CellSize.Height > 0)
                {
                    //Info: Max avilable width excluding padding of both area's
                    int wMax = size.Width + mHVPainter.DisplayRectangle.Width -
                        (this.Padding.Horizontal + mHVPainter.Padding.Horizontal);

                    int mColumns = (wMax / (this.CellSize.Width + mHVPainter.CellSize.Width));

                    Size pa = mHVPainter.DisplayRectangle.Size;
                    pa.Width = mHVPainter.Padding.Horizontal + (mHVPainter.CellSize.Width * mColumns);

                    mHVPainter.ResizeTo(pa);

                    this.Location = new Point(
                        mHVPainter.Location.X + pa.Width + mHVPainter.Padding.Horizontal, this.Location.Y);
                    size.Width = (this.CellSize.Width * mColumns);
                    base.ResizeTo(size);
                }
            }
        }

        public override void RenderSegment(Rectangle clip)
        {
            PaintScheme tsHolder;
            Range tbrange;

            long ms = this.OffsetStates.Start;
            foreach (KeyValuePair<Range, int> ofs in this.OffsetStates)
            {
                tbrange = new Range(ofs.Key.Start - ms, ofs.Key.End - ms);
                tsHolder = this.DrawnOn.PaintSchemes[ofs.Value];
                this.FillCell(tbrange, tsHolder.Background);
                this.DrawForeHelper(tbrange, tsHolder.Foreground);
            }
        }

        protected override string HelperSource(int x, int y, long i)
        {
            //TODO: insted of creating a new array for every turn, 
            // make a copy of the whole date in RenderSegment method
            // and use to encode data.
            byte[] ta = new byte[] { this.DrawnOn.Source[(int)i] };
            return this.DrawnOn.Encoder.GetString(ta, 0, 1);
        }
    }
}
